#include "DraggableTextEdit.h"
#include <QMouseEvent>
#include <QMenu>
#include <QAction>
#include <QWidget>

DraggableTextEdit::DraggableTextEdit(QWidget *parent)
        : QTextEdit(parent), isDragging(false), originalParent(nullptr), isDetached(false)
{
    setPlaceholderText("文本设置-结果展示：......");
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

void DraggableTextEdit::setOriginalParent(QWidget *parent, const QPoint &pos)
{
    originalParent = parent;
    originalPosition = pos;
}

void DraggableTextEdit::returnToOriginalPosition()
{
    if (isDetached && originalParent) {
        // 回到原来的父容器
        setParent(originalParent);
        move(originalPosition);
        setWindowFlags(Qt::Widget); // 清除窗口标志
        show();
        isDetached = false;
    }
}

void DraggableTextEdit::detachFromParent()
{
    if (!isDetached && originalParent) {
        // 脱离父容器，成为独立窗口
        setParent(nullptr);
        setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
        setGeometry(geometry()); // 保持原来的大小
        show();
        isDetached = true;
    }
}

void DraggableTextEdit::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && isDetached) {
        dragStartPosition = event->globalPos() - frameGeometry().topLeft();
        isDragging = true;
    }
    QTextEdit::mousePressEvent(event);
}

void DraggableTextEdit::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons() & Qt::LeftButton) && isDragging && isDetached) {
        // 拖动窗口
        move(event->globalPos() - dragStartPosition);
    }
    QTextEdit::mouseMoveEvent(event);
}

void DraggableTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *menu = createStandardContextMenu();

    // 添加自定义动作
    if (!isDetached) {
        menu->addSeparator();
        menu->addAction("脱离窗口", this, &DraggableTextEdit::detachFromParent);
    } else {
        menu->addSeparator();
        menu->addAction("回到原位", this, &DraggableTextEdit::returnToOriginalPosition);
    }

    menu->exec(event->globalPos());
    delete menu;
}
